<template>
  <div>
    <el-dialog title="定位" :visible.sync="dialog" size="45%" :destroy-on-close="true" :before-close="close"
      :wrapperClosable="true">
      <div class="map-content">
        <el-input clearable prefix-icon="el-icon-search" v-model="key" id="suggestId" class="mapSearchInput"
          placeholder="搜索位置"></el-input>
        <div class="baidumap" id="allmap"></div>

        <div class="searchResult">
          <div class="searchRow">
            <span class="searchTitle">选中地址：</span>
            <el-input class="searchDetails" v-model="tempAddr.locationAddress" readonly></el-input>
            <el-button class="searchBtn" type="primary" @click="submit">确认</el-button>
            <el-button class="searchBtn" @click="close()">取消</el-button>
          </div>
        </div>

      </div>
    </el-dialog>
  </div>
</template>

<script>

  import {BAI_DU_MAP} from "@/constant.js"

  export default {
    data() {
      return {
        dialog: false,
        key: undefined,

        tempAddr: {
          lng: undefined,
          lat: undefined,
          locationAddress: undefined,
          locationProvince: undefined,
          locationCity: undefined,
          locationDistrict: undefined,
          locationStreet: undefined,
          locationStreetNumber: undefined,
          locationBusiness: undefined
        },

      }
    },
    mounted() {
      // const s = document.createElement('script');
      // s.type = 'text/javascript';
      // s.src = BAI_DU_MAP;
      // document.body.appendChild(s);
    },
    methods: {
      close() {
        this.dialog = false;
      },
      open(location) {
        this.reset();
        this.dialog = true;
        this.setData(location);
        var si = setInterval(() => {
          if (window.BMap) {
            this.initMap();
            clearInterval(si);
          }
        }, 500);
      },
      reset() {
        for (let key in this.tempAddr) {
          this.tempAddr[key] = undefined;
        }
      },
      setData(data) {
        if (data) {
          for (let key in this.tempAddr) {
            if (data.hasOwnProperty(key))
              this.tempAddr[key] = data[key];
          }
        }
      },

      initMap() {
        var $this = this;

        var map = new BMap.Map("allmap");
        var point = new BMap.Point(this.tempAddr.lng ? this.tempAddr.lng : 116.331398, this.tempAddr.lat ? this.tempAddr
          .lat : 39.897445); //默认定到北京
        map.centerAndZoom(point, 17);// 缩放比例
        map.enableScrollWheelZoom();
        // map.addControl(new BMap.NavigationControl());
        map.addControl(new BMap.ScaleControl());
        map.addControl(new BMap.OverviewMapControl());
        map.addControl(new BMap.MapTypeControl());

        //首次定位,定位所在城市
        if (this.tempAddr.lng == 0 || this.tempAddr.lng == undefined) {
          var myCity = new BMap.LocalCity();
          myCity.get(function(result) {
            var cityName = result.name;
            map.setCenter(cityName);
          });
        } else { //已有定位记录,显示标记物
          var tempAddr = {
            point: {
              lng: this.tempAddr.lng,
              lat: this.tempAddr.lat
            },
            address: this.tempAddr.locationAddress,
          };
          var marker = new BMap.Marker(tempAddr.point); // 创建标注
          map.addOverlay(marker); // 将标注添加到地图中
          marker.setAnimation(BMAP_ANIMATION_BOUNCE); //跳动的动画
        }

        //地图点击监听
        var geoc = new BMap.Geocoder();
        map.addEventListener("click", function(e) {
          geoc.getLocation(e.point, function(rs) {
            map.clearOverlays(); //清除所有覆盖物
            var marker = new BMap.Marker(rs.point); // 创建标注
            map.addOverlay(marker); // 将标注添加到地图中
            marker.setAnimation(BMAP_ANIMATION_BOUNCE); //跳动的动画

            // 保存值
            $this.tempAddr.lat = rs.point.lat;
            $this.tempAddr.lng = rs.point.lng;
            $this.tempAddr.locationAddress = rs.address;
            $this.tempAddr.locationProvince = rs.addressComponents.province;
            $this.tempAddr.locationCity = rs.addressComponents.city;
            $this.tempAddr.locationDistrict = rs.addressComponents.district;
            $this.tempAddr.locationStreet = rs.addressComponents.street;
            $this.tempAddr.locationStreetNumber = rs.addressComponents.streetNumber;
            $this.tempAddr.locationBusiness = rs.addressComponents.business;
          });
        });

        // 初始化地图,设置城市和地图级别。
        var ac = new BMap.Autocomplete({
          "input": "suggestId",
          "location": map
        });
        ac.addEventListener("onconfirm", function(e) { //鼠标点击下拉列表后的事件
          var value = e.item.value;
          setPlace(value.city, value.district, value.street, value.business, value);
        });

        function setPlace(city, district, street, business, info) {
          map.clearOverlays(); //清除地图上所有覆盖物
          var local = new BMap.LocalSearch(map, { //智能搜索
            onSearchComplete: function() {
              var data = local.getResults().getPoi(0);
              var pp = local.getResults().getPoi(0).point; //获取第一个智能搜索的结果
              map.centerAndZoom(pp, 17);
              map.addOverlay(new BMap.Marker(pp)); //添加标注

              var address = "";
              if (data.province) address += data.province;
              address += city + district;
              if (street) address += street;
              if (business) address += business;

              // 保存值
              $this.tempAddr.lat = pp.lat;
              $this.tempAddr.lng = pp.lng;
              $this.tempAddr.locationAddress = address;
              $this.tempAddr.locationProvince = info.province;
              $this.tempAddr.locationCity = info.city;
              $this.tempAddr.locationDistrict = info.district;
              $this.tempAddr.locationStreet = info.street;
              $this.tempAddr.locationStreetNumber = info.streetNumber;
              $this.tempAddr.locationBusiness = info.business;
            }
          });
          local.search(city + district + street + business);
        }
      },
      submit() {
        var location = Object.assign({}, this.tempAddr);
        this.$parent.saveMapIndex(location);
        this.close();
      }

    }
  }
</script>

<style scoped lang="scss">
  .map-content {
    padding: 10px;
    position: relative;
  }

  .baidumap {
    height: 500px;
    border: 1px solid #C8C9CC;
  }

  /* 去除百度地图版权那行字 和 百度logo */
  .baidumap>.BMap_cpyCtrl {
    display: none !important;
  }

  .baidumap>.anchorBL {
    display: none !important;
  }

  /* 地图上左侧的搜索栏 */
  .mapSearchInput {
    position: absolute;
    z-index: 100;
    top: 20px;
    left: 20px;
    width: 400px;
  }

  /* 搜索结果 */
  .searchResult {
    width: 100%;
    margin-top: 15px;
  }

  .searchRow {
    display: flex;
    align-items: center;

    .searchBtn {
      margin-left: 10px;
    }

    .searchDetails{
      flex: 1;
    }

    .searchTitle{
      white-space: nowrap;
    }
  }
</style>
<style>
  .el-drawer__header {
    -webkit-box-align: center;
    -ms-flex-align: center;
    align-items: center;
    color: #72767b;
    display: -webkit-box;
    display: -ms-flexbox;
    display: flex;
    margin-bottom: 15px;
    padding: 15px 20px 0;
  }

  .el-drawer__body {
    height: calc(100% - 55px) !important;
    overflow-y: auto;
    padding: 5px;
    padding-top: 1px !important;
    border-top: #DDDDDD 1px solid;
    margin-bottom: 62px;
    border-bottom: #DDDDDD 1px solid;
  }


  .el-drawer-footer {
    width: 100%;
    text-align: right;
    padding: 15px 20px;
    background-color: white;
    position: absolute;
    bottom: 0;
  }
</style>
